#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
解析rosdep验证文件，提取ros包名和缺少的三方包名，并保存到CSV文件
"""
import os
import re
import csv
import sys
from pathlib import Path

def parse_rosdep_validation(input_file, output_csv):
    """
    解析rosdep验证文件，提取ros包名和缺少的依赖包名
    
    Args:
        input_file (str): 输入的rosdep验证文件路径
        output_csv (str): 输出的CSV文件路径
    """
    # 检查输入文件是否存在
    if not os.path.exists(input_file):
        print(f"错误：文件 {input_file} 不存在")
        sys.exit(1)
    
    # 准备提取的数据列表
    extracted_data = []
    
    # 定义匹配模式的正则表达式
    # 模式1: 匹配 "包名: No definition of [依赖包] for OS [操作系统]"
    pattern1 = r'^(\S+):\s*No definition of \[(.*?)\] for OS \[\S+\]'
    # 模式2: 匹配 "包名: Cannot locate rosdep definition for [依赖包]"
    pattern2 = r'^(\S+):\s*Cannot locate rosdep definition for \[(.*?)\]'
    
    # 读取并解析文件
    try:
        with open(input_file, 'r', encoding='utf-8') as f:
            for line_num, line in enumerate(f, 1):
                line = line.strip()
                if not line:
                    continue
                
                # 尝试匹配模式1
                match1 = re.match(pattern1, line)
                # 尝试匹配模式2
                match2 = re.match(pattern2, line)
                
                if match1:
                    ros_package = match1.group(1)
                    missing_package = match1.group(2)
                    extracted_data.append([ros_package, missing_package])
                elif match2:
                    ros_package = match2.group(1)
                    missing_package = match2.group(2)
                    extracted_data.append([ros_package, missing_package])
                else:
                    print(f"警告：第{line_num}行无法匹配模式: {line}")
    
    except Exception as e:
        print(f"读取或解析文件时出错: {str(e)}")
        sys.exit(1)
    
    # 写入CSV文件
    try:
        with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
            # 创建CSV写入器
            csv_writer = csv.writer(csvfile)
            
            # 写入表头
            csv_writer.writerow(['ros_package', 'missing_package'])
            
            # 写入数据
            csv_writer.writerows(extracted_data)
        
        print(f"成功解析 {len(extracted_data)} 条记录")
        print(f"数据已保存到: {output_csv}")
        
    except Exception as e:
        print(f"写入CSV文件时出错: {str(e)}")
        sys.exit(1)

def main():
    """
    主函数
    """
    # 设置输入和输出文件路径
    current_dir = os.path.dirname(os.path.abspath(__file__))
    input_file = os.path.join(current_dir, 'rosdep验证.txt')
    output_csv = os.path.join(current_dir, 'rosdep_missing_dependencies.csv')
    
    print("开始解析rosdep验证文件...")
    parse_rosdep_validation(input_file, output_csv)

if __name__ == "__main__":
    main()